package com.x.epspace.common;

import org.codehaus.jackson.map.ObjectMapper;
import java.util.*;
import java.text.*;
import javax.servlet.http.HttpServletRequest;


public class JsonUtil {

	
	static public String toJson(Object o)throws Exception{
		ObjectMapper mapper = new ObjectMapper();
		DateFormat myDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		mapper.getSerializationConfig().setDateFormat(myDateFormat);
		//mapper.getSerializationConfig().setSerializationInclusion(Inclusion.NON_NULL);  
		//objectMapper.configure(SerializationConfig.WRITE_NULL_MAP_VALUES, false);  
		return mapper.writeValueAsString(o);
	}
	
	static public Object getPOJO(Class clazz, String stringjson)throws Exception {
		ObjectMapper mapper = new ObjectMapper();
		DateFormat myDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		mapper.getSerializationConfig().setDateFormat(myDateFormat);
		//String jsonString=mapper.writeValueAsString(removeList(request.getParameterMap()));
		//System.out.println(jsonString);
		Object o=mapper.readValue(stringjson,clazz); 
		return o;
	}
	static public Object getPOJO(Class clazz, HttpServletRequest request)throws Exception {
		ObjectMapper mapper = new ObjectMapper();
		DateFormat myDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		mapper.getSerializationConfig().setDateFormat(myDateFormat);
		String jsonString=mapper.writeValueAsString(removeList(request.getParameterMap()));
		System.out.println(jsonString);
		Object o=mapper.readValue(jsonString,clazz); 
		return o;
	}

	static private Map removeList(Map ParameterMap){
		Map newmap=new HashMap();
		for(String key:(Set<String>)ParameterMap.keySet()){

			String[] value=(String[])ParameterMap.get(key);
			if(value.length==1){
				newmap.put(key, value[0]);
			}else{
				newmap.put(key, value);
			}
	
		}
		return newmap;
	}

	private static class Row {
		String id;
		Object cell = "cell";

		public String getId() {
			return id;
		}

		public void setId(String id) {
			this.id = id;
		}

		public Object getCell() {
			return cell;
		}

		public void setCell(Object cell) {
			this.cell = cell;
		}

	}

}
